using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace MyCollections.Utils
{
    class IOXml
    {
        public static T DeserializeObject<T>(string filepath)
        {
            T result;
            // Create an instance of the XmlSerializer specifying type and namespace.
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(filepath, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);

            // Use the Deserialize method to restore the object's state.
            result = (T)serializer.Deserialize(reader);

            reader.Close();
            fs.Close();

            return result;
        }

        public static void SerializeObject<T>(string filepath, Object obj)
        {
            // Create an instance of the XmlSerializer specifying type and namespace.
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(filepath, FileMode.Create);

            serializer.Serialize(fs, (T)obj);

            fs.Close();
        }

        public static T Load<T>(string filepath)
        {
            return DeserializeObject<T>(filepath);
        }

        public static void Export<T>(string path, Object obj, string filename)
        {
            SerializeObject<T>(path + "/" +filename, obj);
        }
    }
}
